﻿using System;
using System.Reflection;

namespace Hukee.ExcelHelper
{
    public class ReflectionHelper
    {
        /// <summary>
        /// 设置值
        /// </summary>
        /// <typeparam name="T">ExcelColumn特性标识过的类</typeparam>
        /// <param name="strValue">字符串值</param>
        /// <param name="propertyInfo">反射取得的属性信息</param>
        /// <param name="data">对象实体</param>
        public void SetValue<T>(string strValue, PropertyInfo propertyInfo, T data)
        {
            try
            {
                propertyInfo.SetValue(data, Convert.ChangeType(strValue, propertyInfo.PropertyType) ?? default);
            }
            catch (SystemException)
            {
                propertyInfo.SetValue(data, default);
            }
            catch (Exception e)
            {
                throw new Exception($"未提供类型为{propertyInfo.PropertyType.FullName}的String解析转换." + e.Message);
            }
        }

        /// <summary>
        /// 查找反射属性信息（通过属性上的特性ExcelImportColumn修饰的名字对比）
        /// </summary>
        /// <param name="props"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public PropertyInfo GetPropertyByExcelImportColumnName(PropertyInfo[] props, string name)
        {
            //取属性上的自定义特性
            foreach (PropertyInfo propInfo in props)
            {
                var objAttrs = propInfo.GetCustomAttribute(typeof(ExcelImportColumn), true);
                if (objAttrs != null && objAttrs is ExcelImportColumn attr)
                {
                    if (!string.IsNullOrEmpty(attr.ColumnName) && name == attr.ColumnName)
                    {
                        return propInfo;
                    }
                }
            }
            return null;
        }


    }
}
